package cn.bitkit.tools.net;

import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import cn.bitkit.tools.crypto.CertUtil;

/**
 * 
 * @author changbo
 *
 */
@Slf4j
public class SslUtil {

	@SneakyThrows
	public static SSLSocketFactory createSSLSocketFactory() {
		SSLContext sc = SSLContext.getInstance("TLS");
		sc.init(null, new TrustManager[] { createTrustManager() }, new SecureRandom());
		return sc.getSocketFactory();
	}

	@SneakyThrows
	public static SSLSocketFactory createSSLSocketFactory(byte[] certFile, String certKey) {
		SSLContext sc = SSLContext.getInstance("TLS");
		sc.init(null, createTrustManager(certFile, certKey), new SecureRandom());
		return sc.getSocketFactory();
	}
	
	public static X509TrustManager createTrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
	}
	
	public static TrustManager[] createTrustManager(byte[] certFile, String certKey) throws Exception {
		KeyStore keyStore = CertUtil.loadKeyStore(certFile, certKey);
		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		trustManagerFactory.init(keyStore);
		return trustManagerFactory.getTrustManagers();
	}
	
	public static HostnameVerifier createHostnameVerifier() {
		return (hostname, session) -> true;
	}

}
